package com.wyix.dao;

import com.wyix.domain.Product;
import com.wyix.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wangdx
 * @since 2025/8/22
 */
public class ProductDAO {
    //根据实际情况调整批量大小
    private static final int BATCH_SIZE = 500;

    /**
     * 添加商品
     *
     * @param product 要添加的商品
     * @return 添加成功返回true，否则返回false
     */
    public boolean addProduct(Product product) {
        String sql = "INSERT INTO product(name, description, price, stock) VALUES(?, ?, ?, ?)";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, product.getName());
            pstmt.setString(2, product.getDescription());
            pstmt.setDouble(3, product.getPrice());
            pstmt.setInt(4, product.getStock());

            int rows = pstmt.executeUpdate();
            return rows > 0;

        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 批量添加商品
     *
     * @param products 商品列表
     * @return 成功添加的商品数量
     */
    public int batchAddProducts(List<Product> products) {
        String sql = "INSERT INTO product(name, description, price, stock) VALUES(?, ?, ?, ?)";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            conn.setAutoCommit(false); // 关闭自动提交，提高批量操作效率

            int count = 0;
            for (Product product : products) {
                pstmt.setString(1, product.getName());
                pstmt.setString(2, product.getDescription());
                pstmt.setDouble(3, product.getPrice());
                pstmt.setInt(4, product.getStock());

                pstmt.addBatch(); // 添加到批处理
                count++;

                // 达到批量大小执行一次
                if (count % BATCH_SIZE == 0) {
                    pstmt.executeBatch();
                    pstmt.clearBatch();
                }
            }


            // 执行剩余的批处理
            if (count % BATCH_SIZE != 0) {
                pstmt.executeBatch();
            }
            conn.commit(); // 提交事务
            return count;

        } catch (SQLException e) {
            System.out.println("批量添加商品失败");
            try (Connection conn = DBUtil.getConnection()) {
                if (conn != null && conn.isClosed()) {
                    conn.rollback();
                }
            } catch (SQLException ex) {
                System.out.println("批量添加商品失败，回滚事务：" + ex.getMessage());
            }
            return 0;
        }
    }

    /**
     * 根据ID查询商品
     *
     * @param productId 商品ID
     * @return 商品对象，如果不存在则返回null
     */
    public Product findById(int productId) {
        String sql = "SELECT * FROM product WHERE id = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, productId);

            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    Product product = new Product();
                    product.setId(rs.getInt("id"));
                    product.setName(rs.getString("name"));
                    product.setDescription(rs.getString("description"));
                    product.setPrice(rs.getDouble("price"));
                    product.setStock(rs.getInt("stock"));
                    return product;
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 减少商品库存
     *
     * @param conn      数据库连接（用于事务管理）
     * @param productId 商品ID
     * @param quantity  要减少的数量
     * @return 库存更新成功返回true，否则返回false
     */
    public boolean reduceStock(Connection conn, int productId, int quantity) throws SQLException {
        // 先查询当前库存
        String checkStockSql = "SELECT stock FROM product WHERE id = ?";
        try (PreparedStatement checkStmt = conn.prepareStatement(checkStockSql)) {
            checkStmt.setInt(1, productId);
            try (ResultSet rs = checkStmt.executeQuery()) {
                if (rs.next() && rs.getInt("stock") < quantity) {
                    // 库存不足
                    return false;
                }
            }
        }

        // 更新库存
        String updateSql = "UPDATE product SET stock = stock - ? WHERE id = ?";
        try (PreparedStatement updateStmt = conn.prepareStatement(updateSql)) {
            updateStmt.setInt(1, quantity);
            updateStmt.setInt(2, productId);
            int rows = updateStmt.executeUpdate();
            return rows > 0;
        }
    }

    /**
     * 搜索商品
     *
     * @param keyword 搜索关键词
     * @return 符合条件的商品列表
     */
    public List<Product> searchProducts(String keyword) {
        String sql = "SELECT * FROM product WHERE name LIKE ? OR description LIKE ?";
        List<Product> products = new ArrayList<>();

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            String searchPattern = "%" + keyword + "%";
            pstmt.setString(1, searchPattern);
            pstmt.setString(2, searchPattern);

            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    Product product = new Product();
                    product.setId(rs.getInt("id"));
                    product.setName(rs.getString("name"));
                    product.setDescription(rs.getString("description"));
                    product.setPrice(rs.getDouble("price"));
                    product.setStock(rs.getInt("stock"));
                    products.add(product);
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return products;
    }
}
